package com.lg.cms.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.lg.cms.utils.Md5Util;
import com.lg.cms.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @Description: mybatis 配置类, 初始化pageNum到redis缓存, 使用redis.get("cms:pageNum")获取pageNum
 * @Author: wuyuhang
 * @create: 2020-09-21 20:31
 */
@Configuration
@Slf4j
public class MyBatisPlusConfig {


    @Resource
    RedisUtil redisUtil;
    /**
     * 注册分页组件
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        log.info("mybatis plus分页组件注册成功");
        return new PaginationInterceptor();
    }

    /**
     * 注册乐观锁组件
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        log.info("mybatis plus 乐观锁组件 初始化成功");
        return new OptimisticLockerInterceptor();
    }
    @Bean
    public void initPageNum(){
        try{

            Integer pageSize = (Integer) redisUtil.get("cms:pageSize");
            if(pageSize == null){
                pageSize = 20;
                boolean result = redisUtil.set("cms:pageSize", pageSize);
                if(!result){
                    log.error("mybatis plus pageSize初始化失败");
                    System.exit(0);

                }
                log.info("mybatis plus pageSize初始化为:20");
            }else{
                log.info("mybatis plus pageSize读取到为:" + pageSize.toString());
            }
        }catch (Exception ignored){
            log.error("请先安装redis再启动项目");
            System.exit(0);
        }

    }
}